<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title>Redis 客户端处理 - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="Redis 客户端处理">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content="Redis 客户端处理 - 天地维杰网" />
    <meta name="description" content="这个文档说明了 Redis处理网络层客户端：连接，超时，缓冲区和其他包含的类似主题。文档仅适用于 Redis2.6及以上版本。Redis在配置了TCP端口和启用了Unix 套接字启用后 接收客户端连接。当一个新客户端连接被接收，将会执行以下操作。" />
     
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7826003325059020" crossorigin="anonymous"></script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/mac/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />jvm
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/c/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-empty"></i> <br />c语言
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/web3/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-web3"></i> <br />web3
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/redis-client-handling/" itemprop="url">
        Redis 客户端处理
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="2022-10-20">
    2022-10-20
</time>
</span> 
      

  <span class="post-category" >
  &nbsp; | &nbsp;
  <span class="post-meta-item-icon">
    <i class="fa fa-folder-o"></i>
  </span>
  <span class="post-meta-item-text">分类：</span>
  
    <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
      <a href="http://www.shutdown.cn/categories/redis" itemprop="url" rel="index">
        <span itemprop="name">redis</span>
      </a>
      &nbsp; 
    </span>
  
</span>


      
 <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">翻译</span>
</span>

       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">5725 字 ~12分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    
    <div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback"> 翻译文章，原文地址：https://redis.io/docs/reference/clients/</code></pre></div>
    

    

<p>How the Redis server manages client connections</p>

<blockquote>
<p>Redis服务如何管理客户端连接</p>
</blockquote>

<p>This document provides information about how Redis handles clients at the network layer level: connections, timeouts, buffers, and other similar topics are covered here.</p>

<blockquote>
<p>这个文档说明了 Redis处理网络层客户端：连接，超时，缓冲区和其他包含的类似主题。</p>
</blockquote>

<p>The information contained in this document is <strong>only applicable to Redis version 2.6 or greater</strong>.</p>

<blockquote>
<p>文档仅适用于 Redis2.6及以上版本</p>
</blockquote>

<h2 id="accepting-client-connections">Accepting Client Connections</h2>

<p>Redis accepts clients connections on the configured TCP port and on the Unix socket if enabled. When a new client connection is accepted the following operations are performed:</p>

<blockquote>
<p>Redis在配置了TCP端口和启用了Unix 套接字启用后 接收客户端连接。当一个新客户端连接被接收，将会执行以下操作。</p>
</blockquote>

<ul>
<li>The client socket is put in the non-blocking state since Redis uses multiplexing and non-blocking I/O.</li>
</ul>

<blockquote>
<p>客户端套接字设为非阻塞状态，因为Redis使用多路复用非阻塞IO</p>
</blockquote>

<ul>
<li>The <code>TCP_NODELAY</code> option is set in order to ensure that there are no delays to the connection.</li>
</ul>

<blockquote>
<p><code>TCP_NODELAY</code>选项被设置以确保连接无延迟。</p>
</blockquote>

<ul>
<li>A <em>readable</em> file event is created so that Redis is able to collect the client queries as soon as new data is available to read on the socket.</li>
</ul>

<blockquote>
<p>创建一个可读文件事件，这样Redis才可以从客户端队列及时采集从套接字读取的新数据。</p>
</blockquote>

<p>After the client is initialized, Redis checks if it is already at the limit configured for the number of simultaneous clients (configured using the <code>maxclients</code> configuration directive, see the next section of this document for further information).</p>

<blockquote>
<p>客户端初始化以后，Redis检查并发客户端连接数是否已经达到配置的限制（直接使用<code>maxclients</code>配置的）</p>
</blockquote>

<p>When Redis can&rsquo;t accept a new client connection because the maximum number of clients has been reached, it tries to send an error to the client in order to make it aware of this condition, closing the connection immediately. The error message will reach the client even if the connection is closed immediately by Redis because the new socket output buffer is usually big enough to contain the error, so the kernel will handle transmission of the error.</p>

<blockquote>
<p>当Redis因达到最大客户端连接数而无法接受新客户端连接时，它将发给客户端发送错误提示信息，然后立即关闭连接。及时客户端连接立刻被关闭，错误信息也能够到达客户端，因为套接字的输出缓冲区通常足够大到包含错误，所以内核将会处理错误的传输。</p>
</blockquote>

<h2 id="what-order-are-client-requests-served-in">What Order are Client Requests Served In?</h2>

<blockquote>
<p>客户端请求的服务顺序</p>
</blockquote>

<p>The order is determined by a combination of the client socket file descriptor number and order in which the kernel reports events, so the order should be considered as unspecified.</p>

<blockquote>
<p>该顺序由客户端套接字文件描述符编号和内核报告事件的顺序的组合确定，因此应将该顺序视为未指定。</p>
</blockquote>

<p>However, Redis does the following two things when serving clients:</p>

<blockquote>
<p>但是，Redis 在为客户端提供服务时会执行以下两项操作：</p>
</blockquote>

<ul>
<li>It only performs a single <code>read()</code> system call every time there is something new to read from the client socket. This ensures that if we have multiple clients connected, and a few send queries at a high rate, other clients are not penalized and will not experience latency issues.</li>
</ul>

<blockquote>
<p>每次从客户端套接字读取新内容时，它只执行一个“read（）”系统调用。这可确保如果我们连接了多个客户端，并且有几个客户端以高速率发送查询，则其他客户端不会受到惩罚，也不会遇到延迟问题。</p>
</blockquote>

<ul>
<li>However once new data is read from a client, all the queries contained in the current buffers are processed sequentially. This improves locality and does not need iterating a second time to see if there are clients that need some processing time.</li>
</ul>

<blockquote>
<p>然而一从客户端读到新数据，在当前缓冲区中包含的所有请求都会被按顺序处理。这改进了局部性，并且不需要再次迭代以查看是否存在需要一些处理时间的客户端。</p>
</blockquote>

<h2 id="maximum-concurrent-connected-clients">Maximum Concurrent Connected Clients</h2>

<blockquote>
<p>最大并发连接客户端</p>
</blockquote>

<p>In Redis 2.4 there was a hard-coded limit for the maximum number of clients that could be handled simultaneously.</p>

<blockquote>
<p>在Redis 2.4版本，对可以并发处理的客户端的最大数量有了一个硬编码的限制</p>
</blockquote>

<p>In Redis 2.6 and newer, this limit is dynamic: by default it is set to 10000 clients, unless otherwise stated by the <code>maxclients</code> directive in <code>redis.conf</code>.</p>

<blockquote>
<p>在Redis2.6及以后的版本，这个限制是动态的：默认设置为10000个客户端，除非直接在<code>redis.conf</code>中配置<code>maxclients</code>。</p>
</blockquote>

<p>However, Redis checks with the kernel what the maximum number of file descriptors that we are able to open is (the <em>soft limit</em> is checked). If the limit is less than the maximum number of clients we want to handle, plus 32 (that is the number of file descriptors Redis reserves for internal uses), then the maximum number of clients is updated to match the number of clients it is <em>really able to handle</em> under the current operating system limit.</p>

<blockquote>
<p>但是，Redis会与内核一起检查我们能够打开的文件描述符的最大数量是多少（选中了*soft limit*）。如果该限制小于我们要处理的最大客户端数加上32（即Redis为内部使用保留的文件描述符数），那么最大客户端数将被更新，以匹配当前操作系统限制下它“真正能够处理”的客户端数。</p>
</blockquote>

<p>When <code>maxclients</code> is set to a number greater than Redis can support, a message is logged at startup:</p>

<blockquote>
<p>当 <code>maxclients</code> 被设置为超过Redis可以支持的数量，在启动时会在日志中输出信息：</p>
</blockquote>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ ./redis-server --maxclients <span style="color:#0000cf;font-weight:bold">100000</span>
<span style="color:#ce5c00;font-weight:bold">[</span>41422<span style="color:#ce5c00;font-weight:bold">]</span> <span style="color:#0000cf;font-weight:bold">23</span> Jan 11:28:33.179 <span style="color:#8f5902;font-style:italic"># Unable to set the max number of files limit to 100032 (Invalid argument), setting the max clients configuration to 10112.</span></code></pre></div>
<p>When Redis is configured in order to handle a specific number of clients it is a good idea to make sure that the operating system limit for the maximum number of file descriptors per process is also set accordingly.</p>

<blockquote>
<p>当配置 Redis 以处理特定数量的客户端时，最好确保还相应地设置了每个进程的最大文件描述符数的操作系统限制。</p>
</blockquote>

<p>Under Linux these limits can be set both in the current session and as a system-wide setting with the following commands:</p>

<blockquote>
<p>Linux系统下，通过以下命令，既可以设置当前session生效，也可以设置为系统范围设置。</p>
</blockquote>

<ul>
<li><code>ulimit -Sn 100000 # This will only work if hard limit is big enough.</code></li>
<li><code>sysctl -w fs.file-max=100000</code></li>
</ul>

<h2 id="output-buffer-limits">Output Buffer Limits</h2>

<blockquote>
<p>输出缓冲区限制</p>
</blockquote>

<p>Redis needs to handle a variable-length output buffer for every client, since a command can produce a large amount of data that needs to be transferred to the client.</p>

<blockquote>
<p>Redis 需要为每个客户端处理一个可变长度的输出缓冲区，因为命令可能会产生大量需要传输到客户端的数据。</p>
</blockquote>

<p>However it is possible that a client sends more commands producing more output to serve at a faster rate than that which Redis can send the existing output to the client. This is especially true with Pub/Sub clients in case a client is not able to process new messages fast enough.</p>

<blockquote>
<p>但是，客户端可能会发送更多的命令，从而产生更多的输出，以比 Redis 将现有输出发送到客户端的速率更快的速度提供服务。对于 Pub/Sub 客户端尤其如此，以防客户端无法足够快地处理新消息。</p>
</blockquote>

<p>Both conditions will cause the client output buffer to grow and consume more and more memory. For this reason by default Redis sets limits to the output buffer size for different kind of clients. When the limit is reached the client connection is closed and the event logged in the Redis log file.</p>

<blockquote>
<p>两种条件下都会导致客户端输出缓冲区的增长和小号越来越多的内存。因此，默认情况下，Redis为不同类型的客户端设置输出缓冲区大小限制。当达到限制客户端连接会被关闭并且在日志文件中会记录这个事件。</p>
</blockquote>

<p>There are two kind of limits Redis uses:</p>

<blockquote>
<p>Redis使用两种限制：</p>
</blockquote>

<ul>
<li>The <strong>hard limit</strong> is a fixed limit that when reached will make Redis close the client connection as soon as possible.
&gt; <strong>硬限制</strong> 是指达到先之后Redis会立即关闭客户端连接。</li>
<li>The <strong>soft limit</strong> instead is a limit that depends on the time, for instance a soft limit of 32 megabytes per 10 seconds means that if the client has an output buffer bigger than 32 megabytes for, continuously, 10 seconds, the connection gets closed.
&gt; <strong>软限制</strong> 是取决于时间的限制，如每10妙32兆的限制意味着如果客户端的输出缓冲区达到了每秒32兆持续了10秒，那么客户端会被关闭。</li>
</ul>

<p>Different kind of clients have different default limits:</p>

<p>不同类型的客户端有不同的默认限制：</p>

<ul>
<li><strong>Normal clients</strong> have a default limit of 0, that means, no limit at all, because most normal clients use blocking implementations sending a single command and waiting for the reply to be completely read before sending the next command, so it is always not desirable to close the connection in case of a normal client.
&gt; <strong>普通客户端</strong> 默认不限制，因为大多数普通客户端使用阻塞实现来发送单个命令，并在发送下一个命令之前等待完全读取回复，所以在正常客户端的情况下，总是不希望关闭连接。</li>
<li><strong>Pub/Sub clients</strong> have a default hard limit of 32 megabytes and a soft limit of 8 megabytes per 60 seconds.
&gt; <strong>Pub/Sub 客户端</strong> 默认硬限制32兆和软限制为8兆持续60秒。</li>
<li><strong>Replicas</strong> have a default hard limit of 256 megabytes and a soft limit of 64 megabyte per 60 seconds.
&gt; <strong>副本</strong> 默认硬限制256兆和软限制为 64兆持续60秒。</li>
</ul>

<p>It is possible to change the limit at runtime using the <a href="https://redis.io/commands/config-set"><code>CONFIG SET</code></a> command or in a permanent way using the Redis configuration file <code>redis.conf</code>. See the example <code>redis.conf</code> in the Redis distribution for more information about how to set the limit.</p>

<blockquote>
<p>使用 <code>CONFIG SET</code> 命令可以运行中修改限制或者在配置文件<code>redis.conf</code>中永久修改。</p>
</blockquote>

<h2 id="query-buffer-hard-limit">Query Buffer Hard Limit</h2>

<blockquote>
<p>查询缓冲区硬限制</p>
</blockquote>

<p>Every client is also subject to a query buffer limit. This is a non-configurable hard limit that will close the connection when the client query buffer (that is the buffer we use to accumulate commands from the client) reaches 1 GB, and is actually only an extreme limit to avoid a server crash in case of client or server software bugs.</p>

<blockquote>
<p>每个客户端也受查询缓冲区限制的约束。这是一个不可配置的硬限制，当客户端查询缓冲区（即我们用于累积来自客户端的命令的缓冲区）达到 1 GB 时，它将关闭连接，实际上只是一个极端限制，以避免在客户端或服务器软件错误的情况下服务器崩溃。</p>
</blockquote>

<h2 id="client-eviction">Client Eviction</h2>

<blockquote>
<p>客户端驱逐（<font color=red>Redis7.0后才可用</font>）</p>
</blockquote>

<p>Redis is built to handle a very large number of client connections. Client connections tend to consume memory, and when there are many of them, the aggregate memory consumption can be extremely high, leading to data eviction or out-of-memory errors. These cases can be mitigated to an extent using <a href="https://redis.io/docs/reference/clients/#output-buffers-limits">output buffer limits</a>, but Redis allows us a more robust configuration to limit the aggregate memory used by all clients&rsquo; connections.</p>

<blockquote>
<p>Redis 是为处理大量客户端连接而构建的。客户端连接往往会消耗内存，当存在许多客户端连接时，总内存消耗可能非常高，从而导致数据逐出或内存不足错误。这些情况可以使用[输出缓冲区限制]（<a href="https://redis.io/docs/reference/clients/#output-buffers-limits）在一定程度上得到缓解，但Redis允许我们使用更强大的配置来限制所有客户端连接使用的内存之和。">https://redis.io/docs/reference/clients/#output-buffers-limits）在一定程度上得到缓解，但Redis允许我们使用更强大的配置来限制所有客户端连接使用的内存之和。</a></p>
</blockquote>

<p>This mechanism is called <strong>client eviction</strong>, and it&rsquo;s essentially a safety mechanism that will disconnect clients once the aggregate memory usage of all clients is above a threshold. The mechanism first attempts to disconnect clients that use the most memory. It disconnects the minimal number of clients needed to return below the <code>maxmemory-clients</code> threshold.</p>

<blockquote>
<p>此机制称为 <strong>客户端逐出</strong>，它本质上是一种安全机制，一旦所有客户端的总内存使用量超过阈值，它将断开客户端的连接。该机制首先尝试断开使用最多内存的客户端。它会断开返回低于“maxmemory-clients”阈值所需的最小客户端数。</p>
</blockquote>

<p><code>maxmemory-clients</code> defines the maximum aggregate memory usage of all clients connected to Redis. The aggregation takes into account all the memory used by the client connections: the <a href="https://redis.io/docs/reference/clients/#query-buffer-hard-limit">query buffer</a>, the output buffer, and other intermediate buffers.</p>

<blockquote>
<p><code>maxmemory-clients</code>定义了连接到 Redis 的所有客户端的最大内存使用量的总和。这个总和会计入客户端连接使用的所有内存：[查询缓冲区]（<a href="https://redis.io/docs/reference/clients/#query-buffer-hard-limit）、输出缓冲区和其他中间缓冲区。">https://redis.io/docs/reference/clients/#query-buffer-hard-limit）、输出缓冲区和其他中间缓冲区。</a></p>
</blockquote>

<p>Note that replica and master connections aren&rsquo;t affected by the client eviction mechanism. Therefore, such connections are never evicted.</p>

<blockquote>
<p>注意主从副本连接不回受连接驱逐机制的影响。因此，这些连接不会驱逐。</p>
</blockquote>

<p><code>maxmemory-clients</code> can be set permanently in the configuration file (<code>redis.conf</code>) or via the <a href="https://redis.io/commands/config-set"><code>CONFIG SET</code></a> command. This setting can either be 0 (meaning no limit), a size in bytes (possibly with <code>mb</code>/<code>gb</code> suffix), or a percentage of <code>maxmemory</code> by using the <code>%</code> suffix (e.g. setting it to <code>10%</code> would mean 10% of the <code>maxmemory</code> configuration).</p>

<blockquote>
<p><code>maxmemory-clients</code> 可以在配置文件<code>redis.conf</code>中永久配置，或者通过<code>CONFIG SET</code>命令。这个值可以设置为0（将不回限制），以字节为单位的大小（也有可能带有<code>mb</code>或<code>gb</code>后缀），或者是以<code>%</code>为后缀的<code>maxmemory</code>最大内存的百分比。（如设置 10% 意思是最大内存的10%）</p>
</blockquote>

<p>The default setting is 0, meaning client eviction is turned off by default. However, for any large production deployment, it is highly recommended to configure some non-zero <code>maxmemory-clients</code> value. A value <code>5%</code>, for example, can be a good place to start.</p>

<blockquote>
<p>默认是设置为0，说明客户端驱逐默认关闭。然而，一些大型的生产部署，强烈推荐配置一些非零的<code>maxmemory-clients</code>值。如可以从<code>5%</code>开始配置。</p>
</blockquote>

<p>It is possible to flag a specific client connection to be excluded from the client eviction mechanism. This is useful for control path connections. If, for example, you have an application that monitors the server via the <a href="https://redis.io/commands/info"><code>INFO</code></a> command and alerts you in case of a problem, you might want to make sure this connection isn&rsquo;t evicted. You can do so using the following command (from the relevant client&rsquo;s connection):</p>

<blockquote>
<p>可以标记要从客户端逐出机制中排除的特定客户端连接。这对于控制路径连接非常有用。例如，如果您有一个应用程序通过 [&lsquo;INFO&rsquo;]（<a href="https://redis.io/commands/info）">https://redis.io/commands/info）</a> 命令监视服务器，并在出现问题时向您发出警报，则可能需要确保此连接不会被逐出。您可以使用以下命令（从相关客户端的连接）执行此操作：</p>
</blockquote>

<p><a href="https://redis.io/commands/client-no-evict"><code>CLIENT NO-EVICT</code></a> <code>on</code></p>

<p>And you can revert that with:</p>

<p><a href="https://redis.io/commands/client-no-evict"><code>CLIENT NO-EVICT</code></a> <code>off</code></p>

<p>For more information and an example refer to the <code>maxmemory-clients</code> section in the default <code>redis.conf</code> file.</p>

<p>Client eviction is available from Redis 7.0.</p>

<blockquote>
<p>客户端驱逐机制从<font color=red>Redis7.0版本开始可用</font></p>
</blockquote>

<h2 id="client-timeouts">Client Timeouts</h2>

<blockquote>
<p>客户端超时时间</p>
</blockquote>

<p>By default recent versions of Redis don&rsquo;t close the connection with the client if the client is idle for many seconds: the connection will remain open forever.</p>

<blockquote>
<p>默认最近的Redis版本不回关闭客户端连接如果客户端空闲几秒：连接会永远保持打开状态。</p>
</blockquote>

<p>However if you don&rsquo;t like this behavior, you can configure a timeout, so that if the client is idle for more than the specified number of seconds, the client connection will be closed.</p>

<blockquote>
<p>但是，如果您不喜欢这样，则可以配置超时时间，以便在客户端空闲时间超过指定的秒数时，将关闭客户端连接。</p>
</blockquote>

<p>You can configure this limit via <code>redis.conf</code> or simply using <code>CONFIG SET timeout &lt;value&gt;</code>.</p>

<blockquote>
<p>可以在 <code>redis.conf</code>文件中配置或使用 <code>CONFIG SET timeout &lt;value&gt;</code>。</p>
</blockquote>

<p>Note that the timeout only applies to normal clients and it <strong>does not apply to Pub/Sub clients</strong>, since a Pub/Sub connection is a <em>push style</em> connection so a client that is idle is the norm.</p>

<blockquote>
<p>注意这个超时时间只会应用到普通的客户端连接，<strong>不会应用到Pub/Sub客户端连接</strong>，因为 Pub/Sub连接是一个*推送形式*连接，因此客户端空闲是常态。</p>
</blockquote>

<p>Even if by default connections are not subject to timeout, there are two conditions when it makes sense to set a timeout:</p>

<blockquote>
<p>即使默认情况下连接不受超时的影响，设置超时也存在两种情况：</p>
</blockquote>

<ul>
<li>Mission critical applications where a bug in the client software may saturate the Redis server with idle connections, causing service disruption.
<br /></li>
</ul>

<blockquote>
<p>任务关键型应用程序，其中客户端软件中的bug可能会使Redis服务器充满空闲连接，从而导致服务中断。</p>
</blockquote>

<ul>
<li>As a debugging mechanism in order to be able to connect with the server if a bug in the client software saturates the server with idle connections, making it impossible to interact with the server.</li>
</ul>

<blockquote>
<p>作为一种调试机制，以便在客户端软件中的错误使服务器充满空闲连接时能够与服务器连接，从而无法与服务器交互。</p>
</blockquote>

<p>Timeouts are not to be considered very precise: Redis avoids setting timer events or running O(N) algorithms in order to check idle clients, so the check is performed incrementally from time to time. This means that it is possible that while the timeout is set to 10 seconds, the client connection will be closed, for instance, after 12 seconds if many clients are connected at the same time.</p>

<blockquote>
<p>超时不应被视为非常精确：Redis 避免设置计时器事件或运行O(N)算法来检查空闲客户端，因此检查会不时以增量方式执行。这意味着，当超时设置为 10 秒时，如果同时连接多个客户端，客户端连接可能会在12秒后关闭。</p>
</blockquote>

<h2 id="the-client-command">The CLIENT Command</h2>

<blockquote>
<p>客户端命令</p>
</blockquote>

<p>The Redis <a href="https://redis.io/commands/client"><code>CLIENT</code></a> command allows you to inspect the state of every connected client, to kill a specific client, and to name connections. It is a very powerful debugging tool if you use Redis at scale.</p>

<blockquote>
<p>Redis [<code>CLIENT</code>]（<a href="https://redis.io/commands/client）">https://redis.io/commands/client）</a> 命令允许您检查每个已连接客户端的状态、终止特定客户端以及命名连接。如果您大规模使用 Redis，它是一个非常强大的调试工具。</p>
</blockquote>

<p><a href="https://redis.io/commands/client-list"><code>CLIENT LIST</code></a> is used in order to obtain a list of connected clients and their state:</p>

<blockquote>
<p>[<code>CLIENT LIST</code>]（<a href="https://redis.io/commands/client-list）">https://redis.io/commands/client-list）</a> 命令用于获取已连接客户端及其状态的列表：</p>
</blockquote>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-lua" data-lang="lua"><span style="color:#000">redis</span> <span style="color:#0000cf;font-weight:bold">127.0</span><span style="color:#0000cf;font-weight:bold">.0</span><span style="color:#0000cf;font-weight:bold">.1</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">6379</span><span style="color:#ce5c00;font-weight:bold">&gt;</span> <span style="color:#000">client</span> <span style="color:#000">list</span>
<span style="color:#000">addr</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">127.0</span><span style="color:#0000cf;font-weight:bold">.0</span><span style="color:#0000cf;font-weight:bold">.1</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">52555</span> <span style="color:#000">fd</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">5</span> <span style="color:#000">name</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">age</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">855</span> <span style="color:#000">idle</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">flags</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">N</span> <span style="color:#000">db</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">sub</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">psub</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">multi</span><span style="color:#ce5c00;font-weight:bold">=-</span><span style="color:#0000cf;font-weight:bold">1</span> <span style="color:#000">qbuf</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">qbuf</span><span style="color:#ce5c00;font-weight:bold">-</span><span style="color:#000">free</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">32768</span> <span style="color:#000">obl</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">oll</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">omem</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">events</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">r</span> <span style="color:#000">cmd</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">client</span>
<span style="color:#000">addr</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">127.0</span><span style="color:#0000cf;font-weight:bold">.0</span><span style="color:#0000cf;font-weight:bold">.1</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">52787</span> <span style="color:#000">fd</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">6</span> <span style="color:#000">name</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">age</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">6</span> <span style="color:#000">idle</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">5</span> <span style="color:#000">flags</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">N</span> <span style="color:#000">db</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">sub</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">psub</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">multi</span><span style="color:#ce5c00;font-weight:bold">=-</span><span style="color:#0000cf;font-weight:bold">1</span> <span style="color:#000">qbuf</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">qbuf</span><span style="color:#ce5c00;font-weight:bold">-</span><span style="color:#000">free</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">obl</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">oll</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">omem</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">events</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">r</span> <span style="color:#000">cmd</span><span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#000">ping</span></code></pre></div>
<p>In the above example two clients are connected to the Redis server. Let&rsquo;s look at what some of the data returned represents:</p>

<blockquote>
<p>上面的荔枝是两个客户端连接到Redis服务。返回字段如下：</p>
</blockquote>

<ul>
<li><strong>addr</strong>: The client address, that is, the client IP and the remote port number it used to connect with the Redis server.
&gt; <strong>addr</strong>: 客户端地址，即客户端 IP 和用于与 Redis 服务器连接的远程端口号。</li>
<li><strong>fd</strong>: The client socket file descriptor number.
&gt; <strong>fd</strong>: 客户端套接字文件描述符编号。</li>
<li><strong>name</strong>: The client name as set by <a href="https://redis.io/commands/client-setname"><code>CLIENT SETNAME</code></a>.
&gt; <strong>name</strong>: 通过<code>CLIENT SETNAME</code>设置的客户端名称。</li>
<li><strong>age</strong>: The number of seconds the connection existed for.
&gt; <strong>age</strong>: 连接存在的秒数。</li>
<li><strong>idle</strong>: The number of seconds the connection is idle.
&gt; <strong>idle</strong>: 连接空闲秒数。</li>
<li><strong>flags</strong>: The kind of client (N means normal client, check the <a href="https://redis.io/commands/client-list">full list of flags</a>).
&gt; <strong>flags</strong>: 连接类型（N为普通客户端连接，参考<a href="https://redis.io/commands/client-list">full list of flags</a>）</li>
<li><strong>omem</strong>: The amount of memory used by the client for the output buffer.
&gt; <strong>omem</strong>: 客户端输出缓冲区使用的内存量。</li>
<li><strong>cmd</strong>: The last executed command.
&gt; <strong>cmd</strong>: 最后执行的命令。</li>
</ul>

<p>See the <a href="https://redis.io/commands/client-list"><a href="https://redis.io/commands/client-list"><code>CLIENT LIST</code></a></a> documentation for the full listing of fields and their purpose.</p>

<blockquote>
<p>参考<a href="https://redis.io/commands/client-list"><a href="https://redis.io/commands/client-list"><code>CLIENT LIST</code></a></a> 文档</p>
</blockquote>

<p>Once you have the list of clients, you can close a client&rsquo;s connection using the <a href="https://redis.io/commands/client-kill"><code>CLIENT KILL</code></a> command, specifying the client address as its argument.</p>

<blockquote>
<p>通过客户端连接列表，可以通过<code>CLIENT KILL</code>命令关闭指定客户端地址参数的客户端连接。</p>
</blockquote>

<p>The commands <a href="https://redis.io/commands/client-setname"><code>CLIENT SETNAME</code></a> and <a href="https://redis.io/commands/client-getname"><code>CLIENT GETNAME</code></a> can be used to set and get the connection name. Starting with Redis 4.0, the client name is shown in the <a href="https://redis.io/commands/slowlog"><code>SLOWLOG</code></a> output, to help identify clients that create latency issues.</p>

<blockquote>
<p><code>CLIENT SETNAME</code>命令和<code>CLIENT GETNAME</code>命令可以用来设置和获取连接名称。从Redis4.0开始，客户端名称可以在<code>SLOWLOG</code>输出中进行展示了，可以用来帮助识别产生延迟问题的客户端。</p>
</blockquote>

<h2 id="tcp-keepalive">TCP keepalive</h2>

<p>From version 3.2 onwards, Redis has TCP keepalive (<code>SO_KEEPALIVE</code> socket option) enabled by default and set to about 300 seconds. This option is useful in order to detect dead peers (clients that cannot be reached even if they look connected). Moreover, if there is network equipment between clients and servers that need to see some traffic in order to take the connection open, the option will prevent unexpected connection closed events.</p>

<blockquote>
<p>从3.2版起，Redis默认启用TCP keepalive（<code>SO_KEEPALIVE</code>套接字选项），并设置为大约300秒。此选项对于检测死机（即使看起来已连接也无法访问的客户端）很有用。此外，如果客户端和服务器之间的网络设备需要查看一些流量才能打开连接，则该选项将防止意外的连接关闭事件。</p>
</blockquote>

    </div>
    <footer class="post-footer">
     
 
<div class="post-tags">     
     
    <a href="http://www.shutdown.cn/tags/redis" rel="tag" title="redis">#redis#</a>
    
    <a href="http://www.shutdown.cn/tags/client" rel="tag" title="client">#client#</a>
    
    <a href="http://www.shutdown.cn/tags/handle" rel="tag" title="handle">#handle#</a>
    
    <a href="http://www.shutdown.cn/tags/connection" rel="tag" title="connection">#connection#</a>
    
    <a href="http://www.shutdown.cn/tags/%e8%bf%9e%e6%8e%a5" rel="tag" title="连接">#连接#</a>
    
</div>



     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/nacos-apollo-spring-cloud-config-different-and-choose/" rel="next" title="Nacos、Apollo、Config配置中心如何选型？这10个维度告诉你！">
        <i class="fa fa-chevron-left"></i> Nacos、Apollo、Config配置中心如何选型？这10个维度告诉你！
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/c-stop-fget-stdin/" rel="prev" title="c语言终止 fget stdin 输入流">
        c语言终止 fget stdin 输入流 <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

  <ul class="sidebar-nav motion-element">
    <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
      文章目录
    </li>
    <li class="sidebar-nav-overview" data-target="site-overview">
      站点概览
    </li>
  </ul>

    <section class="site-overview sidebar-panel ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">183</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">15</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">224</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
    <div class="post-toc">
        <div class="post-toc-content"><nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#accepting-client-connections">Accepting Client Connections</a></li>
<li><a href="#what-order-are-client-requests-served-in">What Order are Client Requests Served In?</a></li>
<li><a href="#maximum-concurrent-connected-clients">Maximum Concurrent Connected Clients</a></li>
<li><a href="#output-buffer-limits">Output Buffer Limits</a></li>
<li><a href="#query-buffer-hard-limit">Query Buffer Hard Limit</a></li>
<li><a href="#client-eviction">Client Eviction</a></li>
<li><a href="#client-timeouts">Client Timeouts</a></li>
<li><a href="#the-client-command">The CLIENT Command</a></li>
<li><a href="#tcp-keepalive">TCP keepalive</a></li>
</ul></li>
</ul>
</nav></div>
    </div>
</section>

  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2023</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>